var express = require('express');
var router = express.Router();
const query = require('../utils/mysql');
require('express-async-errors');

/*前台api*/
router.get('/hot', async function (req, res, next) {
  const { id } = req.query;
  const result = await query('select * from news where id=?', [id]);
  if (result[0].hits == null) {
    let HITS = 1;
    await query('update news set hits=? where id=?', [HITS, id]);
  } else {
    let HITS = result[0].hits + 1;
    await query('update news set hits=? where id=?', [HITS, id]);
  }
  res.json({
    flag: true,
    data: result
  })
});


router.get('/getNewsList', async function (req, res, next) {
  const result = await query('select * from classnews');
  res.json({
    flag: true,
    data: result
  })
});

router.get('/getCount', async function (req, res, next) {
  const count = await query('select count(*) as count from news');
  res.json({
    flag: true,
    counts: count
  })
});


router.get('/getNews', async function (req, res, next) {
  const { currentPage } = req.query;
  const result = await query('select  a.id,a.title,a.content,b.username,c.classname,a.createdAt,a.updatedAt from news as a left JOIN admins as b on a.authorID = b.id LEFT JOIN classnews as c ON a.classID = c.id limit ?,10', [(currentPage - 1) * 10]);
  res.json({
    flag: true,
    data: result,
  })
});


router.get('/searchNews', async function (req, res, next) {
  const { keyword } = req.query;
  let sql = 'select a.id,a.title,a.content,b.username,c.classname,a.createdAt,a.updatedAt from news as a '
    + 'left join admins as b '
    + 'on a.authorID = b.id '
    + 'left join classnews as c '
    + 'on a.classID = c.id '
    + `where a.title like "%${keyword}%" `
    + 'ORDER BY a.hits DESC '
    + 'LIMIT 10'
  const result = await query(sql);
  console.log(result.length)
  res.json({
    flag: true,
    data: result
  })
});


router.get('/getNewsClass', async function (req, res, next) {
  const result = await query('select * from classnews');
  res.json({
    flag: true,
    data: result
  })
});

module.exports = router;
